package struct.queue.realize;

import java.util.NoSuchElementException;

/**
 * @author: 柒月
 * @date: 2025/5/2 下午6:59
 * @version: 1.0
 */
public class ListDeque {

    private int size;
    private final Node head;
    private final Node tail;

    public ListDeque() {
        this.size = 0;
        head = new Node(0);
        tail = new Node(0);
        head.next = tail;
        tail.prev = head;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int size() {
        return size;
    }

    public void offerFirst(int value) {
        Node newNode = new Node(value);
        newNode.next = head.next;
        head.next.prev = newNode;
        head.next = newNode;
        newNode.prev = head;
        size++;
    }

    public void offerLast(int value) {
        Node newNode = new Node(value);
        newNode.next = tail;
        newNode.prev = tail.prev;
        tail.prev.next = newNode;
        tail.prev = newNode;
        size++;
    }

    public int pollFirst() {
        if (isEmpty()){
            throw new NoSuchElementException();
        }
        int result = head.next.data;
        Node curr = head.next;
        head.next = curr.next;
        curr.next.prev = head;
        size--;
        return result;
    }

    public int pollLast() {
        if (isEmpty()){
            throw new NoSuchElementException();
        }
        int result = tail.prev.data;
        Node curr = tail.prev;
        tail.prev = curr.prev;
        curr.prev.next = tail;
        size--;
        return result;
    }

    public int peekFirst() {
        if (isEmpty()){
            throw new NoSuchElementException();
        }
        return head.next.data;
    }

    public int peekLast() {
        if (isEmpty()){
            throw new NoSuchElementException();
        }
        return tail.prev.data;
    }

    private static class Node {
        private final int data;
        private Node prev;
        private Node next;

        public Node(int data) {
            this.data = data;
        }
    }
}
